package mof.gov.dmdc.view.searchadapter;

import java.text.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import mof.gov.dmdc.view.common.Common;
import mof.gov.dmdc.view.searchitem.AdvancedSearchCriteria;

import oracle.jbo.Row;
import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewCriteriaRow;
import oracle.jbo.ViewObject;

public class AdvancedSearchAdapter extends SearchAdapter implements SearchAdapterInterface {
    public AdvancedSearchAdapter() {
        super();
        operatorMap = new HashMap();
        operatorMap.put("like", "LIKE");
        operatorMap.put("eq", "=");
        operatorMap.put("gt", ">");
        operatorMap.put("lt", "<");
        operatorMap.put("isNull", "IS NULL");
        initTotalList(); //Create total List        
    }

    private List operaterList;
    private List totalList;
    private List<AdvancedSearchCriteria> model;
    private HashMap operatorMap;

    public void addCriteria(ActionEvent event) {
        model.add(getDefaultItem());
    }

    public void removeCriteria(ActionEvent event) {
        if (model.size() == 1) {
            model.clear();
            model.add(getDefaultItem());
        } else {
            model.remove(model.size() - 1);
        }
    }

    @Override
    public void searchAction(ActionEvent event) {
        ViewObject view = getViewObject();
        ViewCriteria oldCriteria;
        try {
            oldCriteria = view.getViewCriteria();
        } catch (Exception e) {
            oldCriteria = null;
        }
        if (oldCriteria != null && !oldCriteria.isEmpty()) {
            oldCriteria.clear();
        }
        ViewCriteria viewCriteria = view.createViewCriteria();
        for (AdvancedSearchCriteria item : model) {
            ViewCriteriaRow criteriaRow = viewCriteria.createViewCriteriaRow();
            String attrName = item.getAttrName();
            int viewType = item.getViewType();
            String attrValue = item.getAttrValue();
            String operator = item.getOperator();
            boolean andConjunction = item.isAndConjunction();
            boolean notConjuction = item.isNotConjunction();
            /*---------------------------setattribute----------------------------*/
            if (operator.equals("isNull")) {
                criteriaRow.setAttribute(attrName, operatorMap.get(operator));
            } else {
                switch (viewType) {
                case 1:
                    criteriaRow.setAttribute(attrName, Integer.parseInt(attrValue));
                    if (operator.equals("like")) {
                        criteriaRow.setOperator(attrName, "=");
                    } else {
                        criteriaRow.setOperator(attrName, (String)operatorMap.get(operator));
                    }
                    break;
                case 2:
                    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
                    Date date = null;
                    try {
                        date = format.parse(attrValue);
                    } catch (ParseException e) {
                        System.out.println("Chan cai khoan nay!");
                    }
                    criteriaRow.setAttribute(attrName, date);
                    if (operator.equals("like")) {
                        criteriaRow.setOperator(attrName, "=");
                    } else {
                        criteriaRow.setOperator(attrName, (String)operatorMap.get(operator));
                    }
                    break;
                default:
                    if (operator.equals("like")) {
                        criteriaRow.setAttribute(attrName, "%" + attrValue.toUpperCase().trim() + "%");
                        criteriaRow.setUpperColumns(true);
                    } else {
                        criteriaRow.setAttribute(attrName, attrValue);
                    }
                    criteriaRow.setOperator(attrName, (String)operatorMap.get(operator));
                    break;
                }
            }

            /*-------------------------- set Conjunction ------------------------*/
            if (andConjunction) {
                if (notConjuction) {
                    criteriaRow.setConjunction(ViewCriteriaRow.VC_CONJ_AND | ViewCriteriaRow.VC_CONJ_NOT);
                } else {
                    criteriaRow.setConjunction(ViewCriteriaRow.VC_CONJ_AND);
                }
            } else {
                if (notConjuction) {
                    criteriaRow.setConjunction(ViewCriteriaRow.VC_CONJ_OR | ViewCriteriaRow.VC_CONJ_NOT);
                } else {
                    criteriaRow.setConjunction(ViewCriteriaRow.VC_CONJ_OR);
                }
            }

            /*--------------------------- add CriteriaRow -----------------------*/
            viewCriteria.addRow(criteriaRow);
        }
        if (!viewCriteria.isEmpty()) {
            view.applyViewCriteria(viewCriteria);
            //view.setMaxFetchSize(-1);
            //view.executeQuery();
            //view.clearCache();            
            //view.setMaxFetchSize(maxFletSize);
            view.executeQuery();
            view.clearCache();
            //currenTotalSize = view.getEstimatedRowCount();
        }
        refreshPage();
    }

    @Override
    public void resetAction(ActionEvent event) {
        model.clear();
        model.add(getDefaultItem());
        ViewObject vo = getViewObject();
        ViewCriteria criteria;
        try {
            criteria = vo.getViewCriteria();
        } catch (Exception e) {
            criteria = null;
        }
        if (criteria != null && !criteria.isEmpty()) {
            //vo.getViewCriteria().clear();
            //vo.setMaxFetchSize(-1);
            //vo.executeQuery();
            //vo.clearCache();            
            //vo.setMaxFetchSize(50);
            //maxFletSize = 50;
            vo.executeQuery();
            vo.clearCache();
            //currenTotalSize = vo.getEstimatedRowCount();
        }      
    }

    public void setOperaterList(List operaterList) {
        this.operaterList = operaterList;
    }

    public List getOperaterList() {
        if (operaterList == null || operaterList.isEmpty()) {
            operaterList = new ArrayList();
            operaterList.add(new SelectItem("eq", "B\u1EB1ng")); //Bằng
            operaterList.add(new SelectItem("like", "Ch\u1EE9a")); //Chứa
            operaterList.add(new SelectItem("gt", "L\u1EDBn h\u01A1n")); //Lớn hơn
            operaterList.add(new SelectItem("lt", "Nh\u1ECF h\u01A1n")); //Nhỏ hơn
            operaterList.add(new SelectItem("isNull", "R\u1ED7ng")); //Rỗng
        }
        return operaterList;
    }

    public void setTotalList(List attrList) {
        this.totalList = attrList;
    }

    public List getTotalList() {
        return totalList;
    }

    public void setModel(List<AdvancedSearchCriteria> model) {
        this.model = model;
    }

    public List<AdvancedSearchCriteria> getModel() {
        if (model == null || model.size() == 0) {
            model = new ArrayList<AdvancedSearchCriteria>();
            model.add(getDefaultItem());
        }
        return model;
    }

    private AdvancedSearchCriteria getDefaultItem() {
        SelectItem item = (SelectItem)totalList.get(0);
        AdvancedSearchCriteria criteria = new AdvancedSearchCriteria(item.getValue().toString(), "", "eq", true, false);
        return criteria;
    }

    private void initTotalList() {
        if (totalList == null || totalList.isEmpty()) {
            ViewObject view = getViewSearchField();
            totalList = new ArrayList();
            do {
                Row row = (view.hasNext()) ? view.next() : view.first();
                String attrName = "";
                String attrType = "";
                String lovName = "";
                String attrLabel = "";
                if (row != null) {
                    try {
                        attrName = row.getAttribute("ColName").toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        attrType = row.getAttribute("ColType").toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        lovName = row.getAttribute("LovName").toString();
                    } catch (Exception e) {
                        lovName = "";
                    }
                    try {
                        attrLabel = row.getAttribute("LabelSearch").toString();
                    } catch (Exception e) {
                        attrLabel = "";
                    }
                    String totalString = attrName + ";" + attrType + ";" + lovName;
                    SelectItem item = new SelectItem(totalString, attrLabel);
                    totalList.add(item);
                }
            } while (view.hasNext());            
        }
    }

    public void refreshModel(ValueChangeEvent valueChangeEvent) {
        Common.refreshComponent(valueChangeEvent.getComponent().getParent());
    }    
}
